<template>
  <div class="pushmsg-container" v-loading="loading">
    <div class="pushmsg-searchView">
      <div class="pushmsg-searchItem">
        <span class="pushmsg-searchTitle">消息ID</span>
        <el-input
          v-model="searchInfo.msgId"
          placeholder="请输入消息ID"
          class="pushmsg-searchInput"
        ></el-input>
      </div>
      <div class="pushmsg-searchItem">
        <span class="pushmsg-searchTitle">来源</span>
        <el-select
          v-model="searchInfo.sendOrigin"
          placeholder="请选择"
          style="width: 100px"
          filterable
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="Web" value="0"></el-option>
          <el-option label="Api" value="1"></el-option>
        </el-select>
      </div>
      <div class="pushmsg-searchItem">
        <span class="pushmsg-searchTitle">类型</span>
        <el-select
          v-model="searchInfo.pushType"
          placeholder="请选择"
          style="width: 100px"
          filterable
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="通知消息" value="0"></el-option>
          <el-option label="透传消息" value="1"></el-option>
        </el-select>
      </div>
      <div class="pushmsg-searchItem">
        <span class="pushmsg-searchTitle">推送日期</span>
        <el-date-picker
          style="width: 300px"
          v-model="searchInfo.date"
          type="daterange"
          align="right"
          unlink-panels
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </div>
      <el-button type="primary" @click="searchClick" class="pushmsg-btn"
        >搜索</el-button
      >
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 100%; margintop: 20px; marginbottom: 10px"
      :row-key="getRowKeys"
      :expand-row-keys="expands"
      @row-click="clickRowHandle"
    >
      <!-- <el-table-column type="selection" width="55" align="center" :reserve-selection="true"></el-table-column> -->
      <el-table-column type="expand">
        <template slot-scope="props">
          <div class="channelBase">
            <div v-for="(element, index) in props.row.detail" :key="index">
              <div class="channelTitle">
                {{ getResult(element, "targetType") }}
                <div class="errorBtn" @click="showRemark(element.remarks)" v-if="element.successNum != element.targetNum">
                  <i class="el-icon-warning-outline"></i>
                </div>
              </div>
              <div class="channelResultView">
                <div class="channelItem">
                  <span class="channelValue">{{ element.targetNum }}</span>
                  <span class="channelKey">目标</span>
                </div>
                <div class="channelItem">
                  <span class="channelValue">{{ element.successNum }}</span>
                  <span class="channelKey">成功</span>
                </div>
              </div>
            </div>
          </div>
          <el-card shadow="never">
            <div slot="header" class="clearfix">
              <span>基本信息</span>
              <el-form label-position="left" size="mini">
                <el-form-item label="推送标题">
                  <span>{{ getResult(props.row, "title") }}</span>
                </el-form-item>
                <el-form-item label="推送内容">
                  <span>{{ getResult(props.row, "content") }}</span>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </template>
      </el-table-column>
      <el-table-column prop="updateDate" label="发送时间" align="center">
        <template slot-scope="scope">
          <div v-html="formatTimestamp(scope.row.updateDate)" />
        </template>
      </el-table-column>
      <el-table-column
        prop="msgId"
        label="消息ID"
        align="center"
      ></el-table-column>
      <!-- <el-table-column prop="content" label="内容" align="center">
          <template slot-scope="scope">
            <span class="show2Lines" style="margin-left: 10px">{{getResult(scope.row, 'content')}}</span>
          </template>
        </el-table-column> -->
      <el-table-column prop="targetNum" label="目标(总)" align="center">
        <template slot-scope="scope">
          <div
            class="tableScopeItem"
            v-html="getResult(scope.row, 'targetNum')"
          />
        </template>
      </el-table-column>
      <el-table-column prop="pushType" label="推送类型" align="center">
        <template slot-scope="scope">
          {{ getResult(scope.row, "pushType") }}
        </template>
      </el-table-column>
      <el-table-column prop="sendOrigin" label="来源" align="center">
        <template slot-scope="scope">
          {{ getResult(scope.row, "sendOrigin") }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="rePushClick(scope.$index, scope.row)"
            plain
            >转发</el-button
          >
          <!-- <el-button
                size="mini" :type="scope.row.zt == '作废' ? 'info' : 'primary'" plain
                @click="getDetail(scope.$index, scope.row)">详情</el-button>
            <el-button v-if="scope.row.zt == '正常' && checkPermission(['管理员','操作人'])"
                size="mini" type="success" plain
                @click="doPrint(scope.$index, scope.row)">{{scope.row.dyzt == '已打印' ? '已打印' : '打印'}}</el-button>
            <el-button
                size="mini" type="warning" plain
                @click="loadLog(scope.$index, scope.row)">日志</el-button>
            <el-button v-if="scope.row.zt == '正常' && checkPermission(['管理员','操作人'])"
                size="mini" type="danger" plain
                @click="doCancel(scope.$index, scope.row)">作废</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNo"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import store from "@/store";
import { getAppEnums, saveKeys } from "@/utils/enums";
import { getPushList, getPushDetail } from "@/api/push.js";
import { copyObj } from '@/utils/util'

export default {
  name: "PushList",
  data() {
    return {
      loading: false,
      appId: "",
      appKey: "",
      appName: "",

      total: 0,
      pageNo: 1,
      pageSize: 10,
      tableData: [],

      searchInfo: {
        // 消息ID
        msgId: "",
        // 来源 0-Web 1-Api
        sendOrigin: "",
        // 类型 0-通知 1-透传
        pushType: "",
        // 日期
        date: "",
      },

      // 获取row的key值
      getRowKeys(row) {
        return row.id;
      },
      // 要展开的行，数值的元素是row的key值
      expands: [],

      // 日期范围
      pickerOptions: {
        selectDate: "",
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
        // 限定范围为三个月 - 90天
        onPick: ({ maxDate, minDate }) => {
          this.selectDate = minDate.getTime();
          if (maxDate) {
            this.selectDate = "";
          }
        },
        // 限定范围为三个月 - 90天
        disabledDate: (time) => {
          if (this.selectDate !== "") {
            const one = 90 * 24 * 3600 * 1000;
            const minTime = this.selectDate - one;
            const maxTime = this.selectDate + one;
            return time.getTime() < minTime || time.getTime() > maxTime;
          }
        },
      },
    };
  },
  created() {
    let info = JSON.parse(sessionStorage.getItem(saveKeys().APP_INFO));
    this.appId = info.appId;
    this.appKey = info.appKey;
    this.appName = info.appName;

    this.getHistoryList();
  },
  methods: {
    // 搜索
    searchClick() {
      this.pageNo = 1;
      this.expands = [];
      this.getHistoryList();
    },
    // 获取历史推送列表
    getHistoryList() {
      var that = this;
      that.loading = true;
      var startTime = "";
      var endTime = "";
      if (that.searchInfo.date != null) {
        startTime =
          that.searchInfo.date[0] == null ? "" : that.searchInfo.date[0];
        endTime =
          that.searchInfo.date[1] == null ? "" : that.searchInfo.date[1];
      }
      let param = {
        appKey: that.appKey,
        pageNo: that.pageNo,
        pageSize: that.pageSize,
        msgId: that.searchInfo.msgId,
        pushType: that.searchInfo.pushType,
        sendOrigin: that.searchInfo.sendOrigin,
        startTime: startTime,
        endTime: endTime,
      };
      getPushList({ ...param })
        .then((response) => {
          // getPushList({...param, ...that.searchInfo}).then(response => {
          if (response != undefined) {
            const data = response.data;
            that.tableData = data.repData.records;
            that.total = data.repData.total;
          }
          that.loading = false;
        })
        .catch((error) => {
          that.loading = false;
        });
    },
    // 获取推送详情
    getPushItemDetail(row) {
      var that = this;
      that.loading = true;
      let param = {
        appKey: that.appKey,
        msgId: row.msgId,
      };
      getPushDetail(param)
        .then((response) => {
          if (response != undefined) {
            const data = response.data;
            that.tableData.forEach((item, index) => {
              if (item.id == row.id) {
                that.tableData[index].detail = data.repData;
                that.expands.push(row.id);
              }
            });
          }
          that.loading = false;
        })
        .catch((error) => {
          that.loading = false;
        });
    },
    // 格式化Table显示内容：推送结果
    getResult(row, key) {
      if (key == "targetNum") {
        // 目标
        return "目标：" + row.targetNum + "</br>成功：" + row.successNum;
      } else if (key == "pushType") {
        // 推送类型 1透传消息 0 普通消息
        if (row.pushType == "1") {
          return "透传消息";
        } else {
          return "通知";
        }
      } else if (key == "targetType") {
        // 通道 1:华为，2:小米，3:oppo，4:vivo，5：极光iOS 6：极光Android
        if (row.targetType == "1") {
          return "华为";
        } else if (row.targetType == "2") {
          return "小米";
        } else if (row.targetType == "3") {
          return "OPPO";
        } else if (row.targetType == "4") {
          return "VIVO";
        } else if (row.targetType == "5") {
          return "极光iOS";
        } else if (row.targetType == "6") {
          return "极光Android";
        }
      } else if (key == "sendOrigin") {
        // 来源 0 Web 1 Api
        if (row.sendOrigin == "0") {
          return "Web";
        } else {
          return "Api";
        }
      } else if (key == "title") {
        // 标题
        let param = JSON.parse(row.operParam);
        return param.title;
      } else if (key == "content") {
        // 内容
        let param = JSON.parse(row.operParam);
        return param.content;
      }

      return row[key];
    },
    // 点击Table的行
    clickRowHandle(row, column, event) {
      if (this.expands.includes(row.id)) {// 如果已经展开，则需要去掉当前数组中的对应id，变成收缩状态
        this.expands = this.expands.filter((val) => val !== row.id);
      } else {// 如果没有展开，调用查询详情接口
        this.getPushItemDetail(row);
      }
    },
    // 点击转发
    rePushClick(index, row) {
      console.log("转发：", row);
      if (row.pushType == 0) {
        // 通知
        this.$router.push({
          path: "/app/pushmsg",
          query: { param: row.operParam },
        });
      } else {
        // 透传
        this.$router.push({
          path: "/app/pushcustommsg",
          query: { param: row.operParam },
        });
      }
    },
    // 时间戳转日期
    formatTimestamp(value) {
      if (value == null) {
        return "";
      }
      var date = new Date(value);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getHistoryList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNo = val;
      this.getHistoryList();
    },
    // 显示错误信息
    showRemark(remark) {
      this.$alert(remark, '错误信息', {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true
        });
    }
  },
};
</script>

<style lang="scss" scoped>
.pushmsg {
  &-container {
    margin: 10px;
  }
  &-searchView {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    align-items: center;
  }
  &-searchItem {
    margin: 10px;
  }
  &-searchTitle {
    color: #333333;
    display: inline-block;
    min-width: 30px;
    font-size: 14px;
    font-weight: bold;
    margin-right: 10px;
    margin-left: 20px;
  }
  &-searchInput {
    width: 200px;
  }
  &-btn {
    width: 100px;
    margin-left: 20px;
  }
}
.tableScopeItem {
  // text-align: left;
}
.show2Lines {
  overflow: hidden; /** 隐藏超出的内容 **/
  word-break: break-all;
  text-overflow: ellipsis; /** 多行 **/
  display: -webkit-box; /** 对象作为伸缩盒子模型显示 **/
  -webkit-box-orient: vertical; /** 设置或检索伸缩盒对象的子元素的排列方式 **/
  -webkit-line-clamp: 2; /** 显示的行数 **/
  margin-bottom: 0.3rem;
}
.channelBase {
  display: flex;
  flex-direction: row;
}
.channelTitle {
  display: flex;
  flex-direction: row;
  padding: 5px;
  width: 150px;
  border-radius: 10px;
  background-color: rgb(243, 243, 243);
  font-size: 14px;
  font-weight: bold;
  position: relative;
}
.errorBtn {
  position: absolute;
  right: 10px;
  cursor: pointer;
}
.channelResultView {
  display: flex;
  flex-direction: row;
  width: 100%;
  align-items: center;
}
.channelItem {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 5px;
  margin-right: 60px;
}
.channelValue {
  color: #333333;
  font-size: 12px;
  font-weight: bold;
  margin: 2px;
}
.channelKey {
  color: #5e5e5e;
  font-size: 12px;
  margin: 2px;
}
</style>
